import json
import argparse

def convert_coco_to_jsonl(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        coco_data = json.load(f)

    images = {image['id']: image for image in coco_data['images']}
    annotations = coco_data['annotations']
    categories = {category['id']: category['name'] for category in coco_data['categories']}

    image_annotations = {image_id: [] for image_id in images.keys()}
    for annotation in annotations:
        image_id = annotation['image_id']
        bbox = annotation['bbox']
        x_min, y_min, width, height = bbox
        x_max = x_min + width
        y_max = y_min + height
        bbox_xyxy = [x_min, y_min, x_max, y_max]
        
        category_id = annotation['category_id']
        label = category_id  # Assuming label is the same as category_id
        category = categories[category_id]
        image_annotations[image_id].append({
            "bbox": bbox_xyxy,
            "label": label,
            "category": category
        })

    with open(output_file, 'w', encoding='utf-8') as f:
        for image_id, image in images.items():
            json_line = {
                "filename": image['file_name'],
                "height": image['height'],
                "width": image['width'],
                "detection": {
                    "instances": image_annotations[image_id]
                }
            }
            f.write(json.dumps(json_line, ensure_ascii=False) + '\n')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Convert COCO annotations to JSONL format")
    parser.add_argument('--input', type=str, required=True, help="Path to the input COCO annotation file")
    parser.add_argument('--output', type=str, required=True, help="Path to the output JSONL file")

    args = parser.parse_args()

    convert_coco_to_jsonl(args.input, args.output)